package cn.cyl.basic.interceptor;

import cn.cyl.basic.jwt.JwtUtils;
import cn.cyl.basic.jwt.Payload;
import cn.cyl.basic.jwt.RsaUtils;
import cn.cyl.user.dto.LoginDto;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.transform.impl.AddInitTransformer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import reactor.core.publisher.Flux;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        //如果有token
        if(token!=null){

//            //就从redis中获取
//            Object obj = redisTemplate.opsForValue().get(token);
//            //如果有值
//            if(obj!=null){
//                //就跟新时间
//                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
//                //放行
//                return true;
//            }
            try {
                //获取对应的公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //用对应的公钥进行解密---如果能成功解密就放行
                //如果解密失败就走catch，向后置拦截器返回消息
                Payload<LoginDto> fromToken = JwtUtils.getInfoFromToken(token, publicKey, LoginDto.class);
                return true;
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeOut\"}");
                return false;
            }

        }
        //跳转到登录页面 - 后端跳不了，因为后端项目没有页面 - 放在前端跳转
        //告诉浏览器我要给你响应一个json数据，编码集为utf-8
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }



}
